package com.atung.parking.config.mybatis;

import com.atung.parking.config.auth.entity.AuthUserEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.Instant;

/**
 * @author Administrator
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前时间的Instant对象
        Long now = Instant.now().toEpochMilli();
        // 定义时间格式
        // 将Instant对象转换为String
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUserEntity authUserEntity = (AuthUserEntity) (authentication.getPrincipal());
        String username = authUserEntity.getUsername();
        // 创建时间
        this.strictInsertFill(metaObject, "creatorTime", () -> now.toString(), String.class);
        // 创建人
        this.strictInsertFill(metaObject, "creatorId", () -> authUserEntity.getUserId().toString(), String.class);
        this.strictInsertFill(metaObject, "creatorName", () -> username, String.class);
    }

    // 更新时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        Long now = Instant.now().toEpochMilli();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUserEntity authUserEntity = (AuthUserEntity) (authentication.getPrincipal());
        String username = authUserEntity.getUsername();
        // 创建时间
        // 更新时间
        this.strictUpdateFill(metaObject, "modifierTime", () -> now.toString(), String.class);
        //修改人
        this.strictUpdateFill(metaObject, "modifierId", () -> authUserEntity.getUserId().toString(), String.class);
        this.strictUpdateFill(metaObject, "modifierName", () -> username, String.class);
    }

}
